<template>
  <a-modal
    class="formModal"
    :title="$t('form.updateCert.title')"
    v-model:open="modalVisible"
    @cancel="close"
    :footer="null"
  >
    <a-form ref="formRef" :model="formState" >
      <a-form-item
        :label="$t('form.updateCert.form_item_1_label')"
        name="fileList"
        :rules="[{ validator: checkFileList, trigger: 'blur' }]"
      >
        <UploadImg
          ref="uploadImg"
          @selectFile="selectFile"
          @removeFile="removeFile"
        ></UploadImg>
      </a-form-item>
    </a-form>
    <div class="footer-btns">
      <a-button @click="close">{{ $t("btnText.cancel") }}</a-button>
      <a-button type="primary" :loding="isSubmitting" @click="submit">{{
        $t("btnText.save")
      }}</a-button>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref } from "vue";
import { postCertificateAdd } from "../../../api/profile";
import { message } from "ant-design-vue";
const modalVisible = ref(false);
const uploadImg = ref();
const close = () => {
  modalVisible.value = false;
  uploadImg.value.clearFile();
  formRef.value.resetFields();
};

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

const show = () => {
  modalVisible.value = true;
};

defineExpose({
  close,
  show,
});
// ===============Upload Img================
const selectFile = (file: File) => {
  formState.value.fileList.push(file);
};

const removeFile = (index: number) => {
  formState.value.fileList.splice(index, 1);
};

// ===============form state================
const formRef = ref();

const formState = ref<{ fileList: File[] }>({
  fileList: [],
});

const checkFileList = (_Rule: any, value: File[]) => {
  if (value.length == 0) {
    return Promise.reject($t("form.updateCert.form_item_1_rules_1"));
  } else {
    return Promise.resolve();
  }
};

const emits = defineEmits(["uploadDown"]);

const isSubmitting = ref(false);

const submit = () => {
  formRef.value.validate().then(() => {
    let successCount = 0;
    formState.value.fileList.forEach(async (file: File) => {
      isSubmitting.value = true;
      let formData = new FormData();
      formData.append("file", file);
      await postCertificateAdd(formData);
      successCount += 1;
      isSubmitting.value = false;
      if (successCount === formState.value.fileList.length) {
        message.success($t("message.upload_success"));
        emits("uploadDown");
        close();
      }
    });
  });
};
</script>
<style scoped lang="less"></style>
